package com.youthfilmic.yuejian.util;

import java.util.*;

import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @title 处理解析xml传输问题
 * */
public class XMLUtil {

	/**
	 * @title xml字符串转化为JSONObject
	 * @author youweixi
	 * @param xmlStr xml字符串
	 * @return JSONObject对象
	 * @time 2015.7.19
	 * */
	public static JSONObject getJsonFromXml(String xmlStr){
		return JSONObject.fromObject(getMapFromXml(xmlStr));
	}

	public static Map<String , String> getMapFromXml(String xmlStr){
		Document document = null;
		try {
			document = DocumentHelper.parseText(xmlStr);
		} catch (DocumentException e) {
			return null;
		}
		Element root = document.getRootElement();
		List<Element> childElements = root.elements();
		Map<String,String> map = new HashMap<String,String>();
		for (Element child : childElements) {
			map.put(child.getName(), child.getStringValue());
		}
		return map;
	}

	public static SortedMap<String , String> getSortMapFromXml(String xmlStr){
		Document document = null;
		try {
			document = DocumentHelper.parseText(xmlStr);
		} catch (DocumentException e) {
			return null;
		}
		Element root = document.getRootElement();
		List<Element> childElements = root.elements();
		SortedMap<String,String> map = new TreeMap<>();
		for (Element child : childElements) {
			map.put(child.getName(), child.getStringValue());
		}
		return map;
	}
	
	/**
	 * @title map转成xml
	 * @author Dxywx
	 * @time 2015.8.15
	 * */
	public static String getXMLFromMap(String rootName , Map<String , String> map){
		Document doc = null;
		Element root = DocumentHelper.createElement(rootName);  
        doc = DocumentHelper.createDocument(root);
        if (map != null){
        	for (Map.Entry<String, String> entry : map.entrySet()){
        		root.addElement(entry.getKey()).addCDATA(entry.getValue());
        	}
        }
        return doc.asXML();
	}
	
}
